<template>
  <div class="use-tmpl" v-loading="isloading">
    <div class="sidebar">
      <div class="tabs">
        <div
          v-for="item in menuList"
          :key="item.id"
          @click="handleSelect(item.key)"
          class="tabList"
          :class="{ active: item.key == activeName }"
        >
          <span>{{ item.name }}</span>
          <el-icon :class="['el-icon-arrow-up', 'icon']">
            <ArrowDown />
          </el-icon>
        </div>
      </div>
      <el-input
        class="search-input"
        placeholder="输入模板名称查询"
        v-model="searchVal"
        @keyup="onSearch"
      >
        <template #append>
          <el-button class="search-btn" :icon="Search" @click="onSearch" />
        </template>
      </el-input>

      <el-scrollbar wrap-class="noScrollX">
        <ul class="tmplList">
          <li
            v-for="item in templates"
            :class="['tmplCard', { selected: item.id == tmplId }]"
            @click="selectTmpl(item)"
            :key="item.id"
          >
            <el-icon
              v-if="activeName == '1'"
              size="12"
              class="user-del-btn"
              @click="delTem(item.id)"
            >
              <Delete
            /></el-icon>
            <p>{{ item.templateName }}</p>
            <p>{{ `创建于${item.createTime}` }}</p>
          </li>
        </ul>
        <el-empty description="暂无数据" v-if="templates.length == 0" />
      </el-scrollbar>
    </div>
    <el-scrollbar class="content" wrap-class="scroll-x-wrap">
      <div class="search-box">
        <p v-if="templateName" class="templateName">{{ templateName }}</p>
        <SearchGroup :value="tmplData" :disabled="true" ref="searchGroup" />
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import SearchGroup from './SearchGroup.vue'
import { simpleUserList, systemSimpleList, deleteUserTemp } from '@/api/ent/advanceSearch/index'
import { Search, User, Setting, Delete } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/public'
const message = useMessage() // 消息弹窗
const searchVal = ref('')
const searchGroup = ref(null)
const templates = ref([])
const tmplData = ref({})
const tmplId = ref('')
const activeIndex = ref('1')
const isloading = ref(false)
const templateName = ref('')

const userTemMap = ref([])
const systemMap = ref([])

const activeName = ref(1)
const menuList = ref([])
// 列表选择
const selectTmpl = (item) => {
  templateName.value = item.templateName
  tmplData.value = JSON.parse(item.templateContent)
  searchGroup.value?.setInitValue(tmplData.value)
  tmplId.value = item.id
}
const TemlateValue = () => {
  return tmplData.value
}
// 用户模板列表
const queryTmplList = async () => {
  const data = await simpleUserList()
  if (data.length) {
    data.forEach((item) => {
      item.createTime = formatDate(item.createTime)
    })
  }
  userTemMap.value = data
}
const delLoading = ref(false)
// 删除用户模板
const delTem = async (id) => {
  if (delLoading.value) return
  await message.delConfirm()
  try {
    delLoading.value = true
    await deleteUserTemp(id)
    message.success('操作成功')
    await queryTmplList()
    handleSelect(1)
  } finally {
    delLoading.value = false
  }
}
// 系统模板列表
const systemTmpLsit = async () => {
  const data = await systemSimpleList()
  if (data.length) {
    data.forEach((item) => {
      item.createTime = formatDate(item.createTime)
    })
  }
  systemMap.value = data
}
onMounted(async () => {
  isloading.value = true
  if (sessionStorage.getItem('templateType') == 'system') {
    menuList.value = [
      {
        key: 2,
        name: '系统模板',
        type: 'system',
        list: []
      }
    ]
    activeName.value = 2
    await systemTmpLsit()
    templates.value = systemMap.value
    if (systemMap.value[0]) selectTmpl(systemMap.value[0])
  } else {
    menuList.value = [
      {
        key: 1,
        name: '用户模板',
        type: 'user',
        list: []
      },
      {
        key: 2,
        name: '系统模板',
        type: 'system',
        list: []
      }
    ]
    activeName.value = 1
    await systemTmpLsit()
    await queryTmplList()
    templates.value = userTemMap.value
    if (userTemMap.value[0]) selectTmpl(userTemMap.value[0])
  }
  isloading.value = false
})
defineExpose({ TemlateValue })
// 模板类型切换
const handleSelect = (key) => {
  activeName.value = key
  if (key == 1) {
    templates.value = userTemMap.value
    if (userTemMap.value[0]) {
      selectTmpl(userTemMap.value[0])
    }
  } else {
    templates.value = systemMap.value
    if (systemMap.value[0]) {
      selectTmpl(systemMap.value[0])
    }
  }
  activeIndex.value = key
}
const onSearch = () => {
  if (searchVal.value) {
    templates.value = templates.value.filter((item) => {
      return item.templateName.indexOf(searchVal.value) > -1
    })
  } else {
    handleSelect(activeIndex.value)
  }
}
</script>

<style lang="scss" scoped>
p {
  margin: 0;
  padding: 0;
}
.tabs {
  width: 100%;
  display: flex;
  color: #333;
  font-size: 14px;
  padding-bottom: 4px;
  border-bottom: 1px solid #f5f7f9;
  .tabList {
    width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
    cursor: pointer;
    position: relative;
    &.active {
      color: #5b83fd;
      &::after {
        content: '';
        position: absolute;
        left: 45%;
        transform: translateX(-50%);
        bottom: 0;
        width: 80px;
        height: 2px;
        background: #5b83fd;
      }
    }
    &:hover {
      color: #5b83fd;
    }
  }

  .content {
    width: 100%;
    overflow: auto;
  }
}
.use-tmpl {
  display: flex;
  align-items: stretch;
  border: 1px solid #ededed;
  border-radius: 4px;
  height: 480px;
}

.sidebar {
  display: flex;
  width: 251px;
  border-right: 1px solid #ededed;
  flex-direction: column;
  font-size: 13px;

  .search-input {
    padding: 8px;
    border-bottom: 1px solid #ededed;

    :deep(.el-input-group__append) {
      background-color: #4b74ff;
      border-color: #4b74ff;
      color: #fff;
    }
  }

  .el-scrollbar {
    flex: 1;

    :deep(.noScrollX) {
      overflow-x: hidden;
    }
    .tmplList {
      padding: 8px;
      li {
        position: relative;
        .user-del-btn {
          position: absolute;
          right: 10px;
          top: 10px;
        }
      }
    }
    .tmplCard {
      background-color: #fafafa;
      padding: 8px;
      border-radius: 5px;
      border: 1px solid #f5f8ff;
      cursor: pointer;
      &.selected {
        border: 1px solid #0052cc;
      }
      :first-child {
        margin-bottom: 8px;
        color: #333;
      }
      :last-child {
        color: #999;
      }
    }
    .tmplCard:hover {
      border: 1px solid #0052cc;
    }
    .tmplCard + .tmplCard {
      margin-top: 8px;
    }
  }
}

.content {
  flex: 1;

  .search-box {
    width: max-content;
    padding: 0 20px;
    transform: scale(0.8);
    transform-origin: top left;
    .templateName {
      margin: 20px 0;
      font-size: 14px;
      color: #333;
    }
  }
}

:deep(.scroll-x-wrap) {
  height: calc(100% + 64px);
}
</style>
